package com.renit.gallery.fragments

import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.renit.gallery.R
import com.renit.gallery.adapter.GalleryAdapter
import com.renit.gallery.models.GalleryViewModel

class HomeFragment : Fragment() {

    private var recyclerView: RecyclerView? = null
    private var swipLayout: SwipeRefreshLayout? = null

    private val galleryViewModel: GalleryViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId) {
            R.id.swipe_to_refresh -> {
                swipLayout?.isRefreshing = true
                galleryViewModel.requestQuery()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onStart() {
        super.onStart()
        setHasOptionsMenu(true)
        recyclerView = activity?.findViewById(R.id.gallery_list)
        swipLayout = activity?.findViewById(R.id.gallery_swipe)

        val galleryAdapter: GalleryAdapter = GalleryAdapter()
        recyclerView?.apply {
            adapter = galleryAdapter
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        }

        galleryViewModel.pageListLiveData.observe(viewLifecycleOwner) {
            galleryAdapter.submitList(it)
            swipLayout?.isRefreshing = false
        }

        swipLayout?.setOnRefreshListener {
            galleryViewModel.requestQuery()
        }

    }

}